using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using LiteVectorIndex.Engine;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.Json;
using System.Threading.Tasks;

namespace LiteVectorIndex
{
    [Icon("pack://application:,,,/LiteVectorIndex;component/Resources/Icon.png")]
    [Category("嵌入式向量库")]
    [OrderWeight(800)]
    public class Cluster_Create : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("集合名")]
        [Description("如果之前加载过同名的集合，本操作将会先将既有集合删除，然后重建。")]
        public object KBName { get; set; }

        [ComboProperty]
        [DisplayName("距离算法")]
        [Description("需根据应用场景采用不同的距离算法。如Cosine适用于语义检索，IP适用于特征值推荐，L2用于度量学习等。")]
        public MetricType MetricTypeInUse { get; set; } = MetricType.Cosine;

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var name = (await dataContext.EvaluateFormulaAsync(KBName))?.ToString() ?? "";

            // 先删除已经存在的集合
            if (CollectionManager.Instance.CollectionExists(name))
            {
                dataContext.Log.AppendLine($"向量集合：{name} 已经被加载到内存，先执行移除操作。");
                CollectionManager.Instance.RemoveCollection(name);
            }

            // 创建新的集合
            var collection = CollectionManager.Instance.CreateNewCollection(name, MetricTypeInUse, true);
            dataContext.Log.AppendLine($"向量集合：{name} 创建成功，维度：{collection.Dimension}，类型：{collection.MetricTypeInUse}，同一化：{collection.NormalizeOnAddAndQuery}。");

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "嵌入式向量库：创建向量集合";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }

    }
}
